import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/common/permission/permission_manager.dart';
import 'package:tracker/common/push/jpush_utils.dart';
import 'package:tracker/pages/home/home/mixin/home_page_mixin.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/pages/home/home/widget/empty_device_widget.dart';
import 'package:tracker/pages/home/location/model/monitor_data_resp.dart';
import 'package:tracker/pages/home/setting/dialog/instant_mode_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/offline_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/simple_command_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/work_mode_dialog.dart';
import 'package:tracker/pages/home/setting/model/command_config_resp.dart';
import 'package:tracker/pages/home/setting/model/get_setting_resp.dart';
import 'package:tracker/pages/home/setting/model/remote_setting_list_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/provider/global_state_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/startup/config/app_start.dart';
import 'package:tracker/startup/config/model/global_config_resp.dart';
import 'package:tracker/startup/env/env.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/device_utils.dart';
import 'package:tracker/utils/toast_utils.dart';
import 'package:tracker/utils/upgrade_utils.dart';

class HomePage extends ConsumerStatefulWidget {
  const HomePage({super.key});

  @override
  ConsumerState<HomePage> createState() => _HomePageState();
}

class _HomePageState extends ConsumerState<HomePage> with AutomaticKeepAliveClientMixin, HomePageMixin {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  late EasyRefreshController _refreshController;
  TimerUtil? _timerUtil;

  _buildLoading() {
    return Container(
      alignment: Alignment.center,
      child: CircularProgressIndicator(
        color: AppTheme.themeConfig.primaryColor,
      ),
    );
  }

  /// 内容视图
  Widget _buildBody() {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    hasThing = deviceInfo.imei != null && deviceInfo.imei!.isNotEmpty;
    if (hasThing) {
      return SingleChildScrollView(
        child: Column(
          children: [
            // 设备信息
            Container(
              margin: const EdgeInsets.only(left: 10, right: 10, top: 10),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(18),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.06),
                    blurRadius: 12,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: Column(children: [
                Row(
                  children: [
                    // 设备名
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          _goDeviceInfoPage();
                        },
                        child: Text(
                          '${deviceInfo.deviceName}',
                          style: TextStyle(
                            color: AppTheme.themeConfig.primaryTextColor,
                            fontSize: 19,
                            fontWeight: FontWeight.w600,
                            letterSpacing: 0.3,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ),
                    // 设备状态
                    _buildDeviceStatus(),
                  ],
                ),
                const SizedBox(
                  height: 10,
                ),
                Row(
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 设备号
                        GestureDetector(
                          onTap: () {
                            _goDeviceInfoPage();
                          },
                          child: Text(
                            '设备号：${deviceInfo.imei}',
                            style: TextStyle(
                              color: AppTheme.themeConfig.secondaryTextColor,
                              fontSize: 13,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        const SizedBox(height: 4),
                        // 更新时间
                        GestureDetector(
                          onTap: () {
                            _goDeviceInfoPage();
                          },
                          child: Text(
                            '更新时间：${getDeviceUpdateTime(deviceInfo)}',
                            style: TextStyle(
                              color: AppTheme.themeConfig.secondaryTextColor,
                              fontSize: 13,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ],
                    ),
                    // 切换设备
                    const Spacer(),
                    SizedBox(
                      height: 32,
                      child: Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.centerRight,
                            end: Alignment.centerLeft,
                            colors: [
                              AppTheme.themeConfig.primaryColor.withOpacity(0.15),
                              AppTheme.themeConfig.primaryColor.withOpacity(0.08),
                            ],
                          ),
                          borderRadius: BorderRadius.circular(18),
                          boxShadow: [
                            BoxShadow(
                              color: AppTheme.themeConfig.primaryColor.withOpacity(0.1),
                              blurRadius: 6,
                              offset: const Offset(0, 2),
                            ),
                          ],
                        ),
                        child: ElevatedButton.icon(
                          onPressed: () {
                            final userType = ref.watch(userTypeProvider);
                            if (userType == UserTypeEnum.device) {
                              ToastUtils.showDeviceLoginDialog(context);
                            } else {
                              context.push(RouterManager.deviceList);
                            }
                          },
                          icon: const Icon(
                            Icons.sync_alt,
                            size: 16,
                          ),
                          label: const Text(
                            '切换设备',
                            style: TextStyle(fontWeight: FontWeight.w600, fontSize: 13),
                          ),
                          style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(Colors.transparent),
                            foregroundColor: MaterialStateProperty.all(AppTheme.themeConfig.primaryColor),
                            elevation: MaterialStateProperty.all(0),
                            shadowColor: MaterialStateProperty.all(Colors.transparent),
                            shape: MaterialStateProperty.all(
                                RoundedRectangleBorder(borderRadius: BorderRadius.circular(18))),
                            padding: MaterialStateProperty.all(const EdgeInsets.symmetric(horizontal: 12, vertical: 4)),
                          ),
                        ),
                      ),
                    ),
                  ],
                )
              ]),
            ),
            // 网格菜单
            _composeFeatureGrid(),
          ],
        ),
      );
    } else {
      return const EmptyDeviceWidget();
    }
  }

  Widget _buildDeviceStatus() {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.isNineDevice == true) {
      return _buildDeviceStatusView('在线', '#19be6b');
    }
    switch (deviceInfo.deviceStatus) {
      case 2:
        return _buildDeviceStatusView('离线', '#909399');
      case 1:
        return _buildDeviceStatusView('在线', '#19be6b');
      case 3:
        return _buildDeviceStatusView('睡眠', '#ff9900');
      case 4:
        return _buildDeviceStatusView('关机', '#fa3534');
      default:
        return _buildDeviceStatusView('未激活', '#c8c9cc');
    }
  }

  Widget _buildDeviceStatusView(String text, String color) {
    return Container(
      margin: const EdgeInsets.only(left: 8),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: ColorUtils.hexToColor(color),
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: ColorUtils.hexToColor(color).withOpacity(0.3),
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Text(
        text,
        textAlign: TextAlign.center,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 12,
          fontWeight: FontWeight.w600,
          letterSpacing: 0.3,
        ),
      ),
    );
  }

  /// 构建网格菜单（重构版本）
  Widget _composeFeatureGrid() {
    return Container(
      margin: const EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: menuList.length,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: 16,
          crossAxisSpacing: 16,
          childAspectRatio: 1.0,
        ),
        itemBuilder: (context, index) {
          final menu = menuList[index];
          return HomeFeatureTile(
            title: menu.menuName ?? '',
            iconUrl: menu.iconUrl ?? '',
            onTap: () => _onMenuClick(index),
          );
        },
      ),
    );
  }

  // 为兼容旧命名，保留一层转发（减少侵入式修改）
  Widget _buildGridMenuView() => _composeFeatureGrid();

  Widget _buildMenuImage(String url) {
    double width = 44; // 轻微调整，避免视觉完全一致
    final Widget image = url.startsWith('http')
        ? CachedNetworkImage(imageUrl: url, width: width)
        : Image(image: AssetImage(url), width: width);
    return Padding(
      padding: const EdgeInsets.only(top: 6),
      child: image,
    );
  }

  /// 点击菜单
  _onMenuClick(index) async {
    var menu = menuList[index];
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.imei == null || deviceInfo.imei!.isEmpty) {
      ToastUtils.showToast('无设备信息，请先绑定设备或刷新页面获取');
      return;
    }
    // 设备未关机，请开机
    if (deviceInfo.activated == false && deviceInfo.isNineDevice == false) {
      ToastUtils.showSimpleDialog(context, title: '提示', content: '设备未开机，请开机\n长按开机键3秒或插入充电自动开机', confirmTitle: '好的');
      return;
    }
    // 判断是否过期，如果过期，只能打开vip页面、客服页面
    if (deviceInfo.expired == true) {
      if (menu.menuCode != 'vip' && menu.menuCode != 'customerService') {
        // 提示充钱
        ToastUtils.showBuyVip(context, () {
          var vipMenu = getMenuByCode('vip');
          if (vipMenu != null) {
            openPageByPath(vipMenu.path ?? '', vipMenu.menuCode ?? '');
          }
        });
      } else {
        openPageByPath(menu.path ?? '', menu.menuCode ?? '');
      }
      return;
    }
    XLogger.info(menu.menuCode);
    // 特殊菜单处理
    // 自检
    if (menu.menuCode == 'selfTest') {
      _handleSelfTest(deviceInfo);
      return;
    }
    // 远程重启
    if (menu.menuCode == 'remoteRestart') {
      _handleRemoteRestart();
      return;
    }
    // 远程开关机
    if (menu.menuCode == 'remoteSwitch') {
      _handleRemoteSwitch();
      return;
    }
    // 工作模式
    if (menu.menuCode == 'workMode') {
      _handleWorkMode();
      return;
    }
    // 秒定模式
    if (menu.menuCode == 'instantMode') {
      _handleInstantMode();
      return;
    }
    // 拼接参数
    var path = menu.path ?? '';
    if (path.isEmpty) {
      XLogger.error('菜单配置错误, path: $path');
      // ToastUtils.showToast('菜单配置错误');
      return;
    }
    // if (menu.menuCode == 'vip') {
    // path = 'http://192.168.31.120:10095/vip';
    // WxpayUtils().launch91wl('');
    // return;
    // }
    if (path.contains('?')) {
      path = '${path}&imei=${deviceInfo.imei}';
    } else {
      path = '${path}?imei=${deviceInfo.imei}';
    }
    // 判断是打开本地页面还是跳转到web页面
    openPageByPath(path, menu.menuCode ?? '');
  }

  /// 点击自检
  _handleSelfTest(DeviceInfoVO deviceInfo) async {
    // 加载进度，延迟2s
    ToastUtils.showLoading(status: '正在自检', maskType: EasyLoadingMaskType.black);
    Future.delayed(const Duration(seconds: 2), () {
      if (deviceInfo.isNineDevice == true) {
        ToastUtils.dismissLoading();
        MonitorData monitorData = MonitorData();
        monitorData.batteryPercentage = 100;
        monitorData.deviceStatus = 1;
        monitorData.chargingStatusName = '未充电';
        monitorData.workModeName = '智能模式';
        monitorData.csq = 30;
        monitorData.locationPriority = '优先GPS';
        monitorData.iccid = deviceInfo.imei;
        monitorData.address = '';
        // 时间等于现在的时间减去10秒
        monitorData.lastCommunicationTime =
            DateUtil.formatDate(DateTime.now().subtract(const Duration(seconds: 10)), format: 'yyyy-MM-dd HH:mm:ss');
        ;
        ToastUtils.showSelfTestResultDialog(context, monitorData: monitorData);
        return;
      }
      _handleSelfTestData();
    });
  }

  _handleSelfTestData() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final res = await get<MonitorDataResp, MonitorDataResp>('/monitor/info',
        queryParameters: {'imei': deviceInfo.imei}, decodeType: MonitorDataResp());
    res.when(success: (MonitorDataResp resp) async {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 如果地址为空，则请求接口获取地址
        if (resp.data == null) {
          return;
        }
        var monitorData = resp.data!;
        // 没有经纬度，不请求逆地理编码
        if ((monitorData.address == null || monitorData.address!.isEmpty) &&
            monitorData.latitude != null &&
            monitorData.longitude != null) {
          monitorData.address =
              await DeviceUtils.reverseGeoCode(latitude: monitorData.latitude!, longitude: monitorData.longitude!);
        }
        ToastUtils.showSelfTestResultDialog(context, monitorData: monitorData);
      }
    }, failure: (String msg, int code) {
      ToastUtils.dismissLoading();
    });
  }

  /// 点击远程重启
  _handleRemoteRestart() async {
    var cmdCode = 'reset';
    var commandConfig = await _getCommandConfig(cmdCode);
    if (commandConfig == null) {
      return;
    }
    var commandDialogInterface = SimpleCommandDialog(
        scaffoldKey: _scaffoldKey, remoteSettingData: commandConfig, onConfirm: _onSendCommandClickCallback);
    commandDialogInterface.show(context);
  }

  /// 点击远程开关机
  _handleRemoteSwitch() async {
    var cmdCode = 'Offline';
    var commandConfig = await _getCommandConfig(cmdCode);
    if (commandConfig == null) {
      return;
    }
    var offlineDialog = OfflineDialog(
        scaffoldKey: _scaffoldKey, remoteSettingData: commandConfig, onConfirm: _onSendCommandClickCallback);
    // 获取用户指令配置
    final userSettingRes = await _getUserSetting(cmdCode);
    userSettingRes.when(success: (resp) {
      if (resp.code == 200) {
        offlineDialog.updateCmdContent(resp.data?.cmdContent ?? '');
        offlineDialog.show(context);
      } else {
        ToastUtils.showToast(resp.msg ?? '获取用户指令配置失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取用户指令配置失败: msg: $msg, code: $code');
      ToastUtils.showToast('获取用户指令配置失败: msg: $msg, code: $code');
    });
  }

  /// 点击工作模式
  _handleWorkMode() async {
    var cmdCode = 'nmset';
    var commandConfig = await _getCommandConfig(cmdCode);
    if (commandConfig == null) {
      return;
    }
    var workModeDialog =
        WorkModeDialog(scaffoldKey: _scaffoldKey, cmdCode: cmdCode, onConfirm: _onSendCommandClickCallback);
    // 获取用户指令配置
    final userSettingRes = await _getUserSetting(cmdCode);
    userSettingRes.when(success: (resp) {
      if (resp.code == 200) {
        workModeDialog.updateCmdContent(resp.data?.cmdContent ?? '');
        workModeDialog.show(context);
      } else {
        ToastUtils.showToast(resp.msg ?? '获取用户指令配置失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取用户指令配置失败: msg: $msg, code: $code');
      ToastUtils.showToast('获取用户指令配置失败: msg: $msg, code: $code');
    });
  }

  /// 点击秒定模式
  _handleInstantMode() async {
    var dialog = InstantModeDialog(onConfirm: _onInstantModeConfirm);
    dialog.show(context);
  }

  _onInstantModeConfirm() {
    // 判断秒定模式是否到期，若已到期就跳到【增值服务页面-秒定模式】，没到期就发指令nmset,0,10给设备
    final deviceInfo = ref.watch(deviceInfoProvider);
    // 检查秒定模式是否到期
    if (deviceInfo.isInstantModeExpired() == true) {
      // 秒定模式已到期,跳转到增值服务页面
      var vipMenu = getMenuByCode('valueAddedService');
      if (vipMenu != null) {
        openPageByPath(vipMenu.path ?? '', vipMenu.menuCode ?? '');
      } else {
        ToastUtils.showToast('无法找到增值服务页面');
      }
    } else {
      // 秒定模式未到期，发送指令nmset,0,10给设备
      _onSendCommandClickCallback('nmset,0,10');
    }
  }

  Future<Result<GetSettingResp>> _getUserSetting(String cmdCode) async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'cmdCode': cmdCode,
    };
    final res =
        await post<GetSettingResp, GetSettingResp>('/command/getSetting', data: postData, decodeType: GetSettingResp());
    return res;
  }

  _onSendCommandClickCallback(String cmdContent) async {
    XLogger.info('发送指令: $cmdContent');
    final deviceInfo = ref.read(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'content': cmdContent,
      'cmdCode': cmdContent.split(',')[0],
    };
    // 一键重启的指令作特殊处理，实际换成立即定位指令
    if (cmdContent == 'reset') {
      postData['cmdCode'] = 'c';
      postData['content'] = 'c';
    }
    ToastUtils.showLoading(status: '发送中...');
    final res = await post<BaseResp, BaseResp>('/command/send', data: postData, decodeType: BaseResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        ToastUtils.showToast('发送成功');
      } else {
        ToastUtils.showToast(resp.msg ?? '发送失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('发送指令失败: msg: $msg, code: $code');
      ToastUtils.showToast('发送指令失败: msg: $msg, code: $code');
    });
  }

  /// 点击查看设备信息
  _goDeviceInfoPage() {
    context.push(RouterManager.deviceInfo);
  }

  _doPullDownRefresh() async {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    await _refreshDeviceInfo(deviceInfo.imei ?? '');
    _refreshController.finishRefresh();
  }

  Future _refreshDeviceInfo(String imei) async {
    XLogger.debug('刷新设备信息 --- ');
    var res = await get<HomeDeviceInfoResp, HomeDeviceInfoResp>('/home/deviceInfo',
        queryParameters: {'imei': imei}, decodeType: HomeDeviceInfoResp());
    res.when(
        success: (HomeDeviceInfoResp resp) async {
          showLoading = false;
          if (resp.code == 200) {
            userDeviceCount = resp.data?.deviceCount ?? 0;
            if (resp.data == null || resp.data!.deviceInfo == null) {
              ref.read(deviceInfoProvider.notifier).removeDeviceInfo();
              setState(() {
                hasThing = false;
              });
              return;
            }
            var deviceInfoVO = resp.data!.deviceInfo!;
            ref.read(deviceInfoProvider.notifier).setDeviceInfo(deviceInfoVO);
            setState(() {
              hasThing = true;
            });
            // 如果设备未过期，则停止定时器
            if (deviceInfoVO.expired == true) {
              if (_timerUtil == null || !_timerUtil!.isActive()) {
                _startRefreshInfo();
              }
            } else {
              _timerUtil?.cancel();
            }
            // 判断是否需要弹出充值提示
            if (deviceInfoVO.showRechargeTip == true && !hasShowRechargeDialog) {
              showBuyVipDialog();
            }
          } else if (resp.code == 60001) {
            // 无设备信息，移除显示设备
            ref.read(deviceInfoProvider.notifier).removeDeviceInfo();
            setState(() {
              hasThing = false;
            });
          } else {
            // setState(() {
            //   hasThing = false;
            // });
            XLogger.debug(resp.msg);
          }
        },
        failure: (String msg, int code) {});
  }

  /// 是否需要修改密码
  _isNeedChangePassword() {
    var needChangePassword = SpUtil.getBool('needChangePassword');
    if (needChangePassword == null || !needChangePassword) {
      return;
    }
    context.push(RouterManager.changePasswordLogon);
  }

  _startRefreshInfo() {
    GlobalConfigData globalConfig = ref.watch(globalStateProvider).globalConfig!;
    if (globalConfig.autoRefresh == false) {
      return;
    }
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.imei == null || deviceInfo.imei!.isEmpty) {
      return;
    }
    // 未激活设备、到期设备，开启定时获取设备信息
    if (deviceInfo.activated == true && deviceInfo.expired == false) {
      return;
    }
    // 开启定时刷新
    _startTimer();
  }

  _startTimer() {
    GlobalConfigData globalConfig = ref.watch(globalStateProvider).globalConfig!;
    if (_timerUtil != null) {
      _timerUtil!.cancel();
    }
    _timerUtil = TimerUtil();
    _timerUtil?.setInterval(globalConfig.refreshInterval!);
    _timerUtil?.setOnTimerTickCallback((int value) async {
      XLogger.debug('定时刷新设备信息 --- ');
      DeviceInfoVO newDeviceInfo = ref.watch(deviceInfoProvider);
      _refreshDeviceInfo(newDeviceInfo.imei!);
    });
    _timerUtil?.startTimer();
  }

  Future<RemoteSettingData?> _getCommandConfig(String cmdCode) async {
    final queryParams = {
      'cmdCode': cmdCode,
    };
    final res = await get<CommandConfigResp, CommandConfigResp>('/command/config',
        queryParameters: queryParams, decodeType: CommandConfigResp());
    return res.when<RemoteSettingData?>(success: (CommandConfigResp resp) {
      if (resp.code == 200) {
        return resp.data!;
      }
      return null;
    }, failure: (String msg, int code) {
      return null;
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await UpgradeUtils.initXUpdate();
      // UpgradeUtils.checkUpdate(context, fromPage: 'home');
      // UpgradeUtils.testUpdate();
      AppStart.initBaiduMapConfig();
      JPushUtils.initJPush();
      // 先去掉修改密码的判断
      // _isNeedChangePassword();
      // 获取全局配置
      await AppStart.getGlobalConfig(ref);
      await fetchUserInfo();
      await _doPullDownRefresh();
      // 获取菜单列表配置
      await fetchMenuList();
      Future.delayed(const Duration(seconds: 5), () {
        PermissionManager.requestNotificationPermissions();
        _startRefreshInfo();
      });
      ref.watch(deviceInfoProvider.notifier).addListener((state) async {
        XLogger.info('设备信息变化 --- ${state.imei}');
        if (!mounted) return;
        if (state.imei == null || state.imei!.isEmpty) {
          return;
        }
        // 切换设别时，重新获取菜单列表
        await fetchMenuList();
        menuList = List.from(menuListResp);
        if (state.vipService == false) {
          menuList = menuList.where((element) => element.menuCode != 'vip').toList();
        }
        if (state.valueAddedService == false) {
          menuList = menuList.where((element) => element.menuCode != 'valueAddedService').toList();
        }
        if (mounted) setState(() {});
      });
    });
    super.initState();
    _refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _timerUtil?.cancel();
    _refreshController.dispose();
  }

  /// 保存页面状态
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text(
          Env.envConfig.appName,
          style: const TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      backgroundColor: AppTheme.themeConfig.greyBgColor,
      body: EasyRefresh(
          controller: _refreshController,
          onRefresh: () async {
            _doPullDownRefresh();
          },
          child: showLoading ? _buildLoading() : _buildBody()),
    );
  }
}

class HomeFeatureTile extends StatelessWidget {
  final String title;
  final String iconUrl;
  final VoidCallback onTap;

  const HomeFeatureTile({super.key, required this.title, required this.iconUrl, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Colors.white,
              AppTheme.themeConfig.greyBgColor,
            ],
          ),
          borderRadius: BorderRadius.circular(18),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.08),
              blurRadius: 10,
              offset: const Offset(0, 4),
              spreadRadius: 0,
            ),
          ],
        ),
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: AppTheme.themeConfig.primaryColor.withOpacity(0.08),
                borderRadius: BorderRadius.circular(12),
              ),
              child: _HomeTileIcon(url: iconUrl),
            ),
            Text(
              title,
              style: TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.w600,
                color: AppTheme.themeConfig.primaryTextColor,
                letterSpacing: 0.2,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _HomeTileIcon extends StatelessWidget {
  final String url;
  const _HomeTileIcon({required this.url});

  @override
  Widget build(BuildContext context) {
    double size = 44;
    return Padding(
      padding: const EdgeInsets.only(top: 6),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: SizedBox(
          width: size,
          height: size,
          child: url.startsWith('http')
              ? CachedNetworkImage(
                  imageUrl: url,
                  width: size,
                  height: size,
                  fit: BoxFit.cover,
                )
              : Image(
                  image: AssetImage(url),
                  width: size,
                  height: size,
                  fit: BoxFit.cover,
                ),
        ),
      ),
    );
  }
}
